package com.example.demo.service.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.internal.OSSUtils;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.example.demo.common.config.AliyunConfig;
import com.example.demo.common.enums.CustomizeEnum;
import com.example.demo.common.handler.CustomException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Objects;
import java.util.Random;

/**
 * @Author: ak
 * @Date: 2020/3/31 23:04
 */
@Slf4j
@Service
public class UploadPicService {
    @Autowired
    private OSS ossClient;

    @Autowired
    private AliyunConfig config;

    public URL imgUpload(MultipartFile file) {
        try {
            if (file.getSize() <= 0) {
                throw new CustomException(CustomizeEnum.IMG_ERROR);
            }
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
            String fileName=System.currentTimeMillis()+".png";
            ossClient.putObject(config.getBucketName(), fileName, file.getInputStream());
            URL url = ossClient.generatePresignedUrl(config.getBucketName(), fileName, expiration);
            System.out.println(url);
            return url;
        } catch (Exception e) {
            log.error("上传失败！");
            log.error(e.getMessage());
        }
        return null;
    }
}
